package com.zhuangjie.mvc.exception;

import com.zhaungjie.base.conduit.R;
import com.zhaungjie.base.conduit.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
@Slf4j
@RestControllerAdvice(annotations = {RestController.class})
public class GlobalExceptionControllerAdvice {
    /**
     * 数据校验异常
     * 数据检验有三种异常：https://blog.csdn.net/HD243608836/article/details/116239908
     * @param e
     * @return {@link R}
     */
    @ExceptionHandler(BindException.class)
    public R handleValidException(BindException e) {
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        HashMap<String, String> errMap = new HashMap<>(8);
        e.getBindingResult().getFieldErrors().forEach(item->{

            String field = item.getField();
            String message = item.getDefaultMessage();
            if(errMap.get(field) != null) {
                // 之前已经存在，追加信息
                message = errMap.get(field) +  ("," +message);
            }
            errMap.put(field,message);
        });
        return R.error(ResultCode.PARAM_ERROR).data(errMap);
    }


    @ExceptionHandler(Exception.class)
    public R allException(Exception e) {
        e.printStackTrace();
        log.error("出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        // e.printStackTrace();
        return R.error(ResultCode.FAIL.getCode(),e.getMessage());
    }



}